#!/bin/bash
set -e

TOOLS_DIR=$(dirname "$PWD")
KERNEL_DIR=${TOOLS_DIR}/packaging/kernel/kata-linux-5.10-96
KMOD_INSTALL_DIR=${KERNEL_DIR}/kmod_install_path
KMOD_DIR=${KMOD_INSTALL_DIR}/lib/modules/5.10.134-csv+

# 该文件必须拷贝到当前目录
ROCK_DRIVER_PATH=`pwd`/rock-5.7.1-6.2.17-kata.deb


if [ `id -u` -ne 0 ]; then
	echo "Must be run as root!"
	exit 1
fi

# 编译module和linux header
mkdir -p KMOD_INSTALL_PATH
pushd ${KERNEL_DIR}
make modules_install INSTALL_MOD_PATH=${KMOD_INSTALL_DIR}
popd

export KERNEL_MODULES_DIR=${KMOD_DIR}
# 制作rootfs
AGENT_INIT=yes USE_DOCKER=true SECCOMP=no EXTRA_PKGS="kmod" ./rootfs-builder/rootfs.sh -r "${PWD}/ubuntu_rootfs" ubuntu

REMOTE_PATH=/hygon-devkit/4.0/2025-01-01/csv/dcu
# 检查当前路径下是否有linux-headers-5.10.134-csv+*.deb
if [ ! -e linux-headers-5.10.134-csv+*.deb ]; then
    echo "linux-headers-5.10.134-csv+*.deb"
    FILE_NAME=$(/opt/hygon/tools/sftp list $REMOTE_PATH | grep -oP "linux-headers-5.10.134-csv+.*?\.deb$")
    /opt/hygon/tools/sftp download $REMOTE_PATH/$FILE_NAME ./$FILE_NAME
fi

# 把kernel header安装包拷贝到rootfs中
cp linux-headers-5.10.134-csv+*.deb ubuntu_rootfs/root -v
# 把 rock驱动安装包拷贝到rootfs中
cp ${ROCK_DRIVER_PATH} ubuntu_rootfs/root -v
# 把安装脚本拷贝到rootfs中
cp install_in_chroot.sh ubuntu_rootfs/root -v

# 利用chroot安装deb包
mount -t sysfs -o ro none ${ROOTFS_DIR}/sys
mount -t proc -o ro none ${ROOTFS_DIR}/proc
mount -t tmpfs none ${ROOTFS_DIR}/tmp
mount -o bind,ro /dev ${ROOTFS_DIR}/dev
mount -t devpts none ${ROOTFS_DIR}/dev/pts
